package com.qf.application.uploadimage;

import com.qf.application.utils.result.Result;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.*;
import java.util.UUID;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

@RestController
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @PostMapping("/upload")
   public String uploadFile(@RequestParam("file")MultipartFile file) throws IOException {
        //获取到的图片全名
        String fileName = file.getOriginalFilename();
        System.out.println("fileName = " + fileName);
        //截取 后缀
        String substring1 = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("substring = " + substring1);
        //重新编写 用uuid图片名称
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String replace = uuid + substring1;
        System.out.println("replace = " + replace);

        File file1 = new File(System.getProperty("user.dir")
                +"/src/main/resources/img/"+replace);

        System.out.println("file1 = " + file1);


        if(!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        file.transferTo(file1);
        System.out.println(file1.getAbsoluteFile());

        String url = "http://localhost:2233/img/"+replace;
        //return Result.success(url,"上传成功");
        return url;
   }
}